package jutf8search;

import java.io.UnsupportedEncodingException;

/**
 * Various methods used in a variety of classes in the jutf8search package.
 * 
 *
 */
public class Utilities
{
	/**
	 * Gets the bytes representing the String.
	 * @param text The String to get the bytes from
	 * @return The UTF-8 bytes from the String.
	 */
	public static byte[] getBytes(String text)
    {
        byte[] bytes = null;
		try
        {
			bytes = text.getBytes("UTF-8");
		}
        catch (UnsupportedEncodingException e)
        {
			System.err.println("Error converting string \""+text+"\" to bytes");
			System.err.println("This implies that the UTF-8 encoding is not present in this version of Java");
		}
        return bytes;
    }
     
	/**
     * Count the number of characters in a byte[], up to position pos in the byte[].
     * @param text The byte[] to search
     * @param pos The position in the array to stop at. If -1, the whole array is searched.
     * @return A long representing the number of characters in the byte[] to position pos.
     */
	public static long countChars(byte[] text, long pos)
	{
		long chars = 0;
		if(pos == -1) pos = text.length;
		for(int i=0; i<text.length;)
		{
			if (i >= pos) return chars;
			int unsignedByte = text[i] & 0xFF;
			if(unsignedByte <= 0x7F){
				++i; ++chars;
			}else if(unsignedByte <= 0xDF && unsignedByte >= 0xC2){
				i += 2; ++chars;
			}
			else if(unsignedByte <= 0xEF && unsignedByte >= 0xE0){
				i += 3; ++chars;
			}
			else if(unsignedByte <= 0xF4 && unsignedByte >= 0xF0){
				i += 4; ++chars;
			}
			else{
				++i;
			}
		}
		return chars;
	}
    
	/**
	 * Returns the number of bytes that the character will represent.
	 * @param b The byte to check
	 * @return The number of bytes that the character will be.
	 */
    public static int skipBytes(byte b)
    {
        int unsignedByte = b & 0xFF;
		if(unsignedByte <= 0x7F){
			return 1;
		}else if(unsignedByte <= 0xDF && unsignedByte >= 0xC2){
			return 2;
		}
		else if(unsignedByte <= 0xEF && unsignedByte >= 0xE0){
			return 3;
		}
		else if(unsignedByte <= 0xF4 && unsignedByte >= 0xF0){
			return 4;
		}
		return 1;
    }
}
